package com.winning.sx.microframework.common.util;

import com.winning.dapi.data.entity.DataTable;
import org.apache.commons.beanutils.PropertyUtilsBean;

import javax.servlet.http.HttpServletRequest;
import java.beans.PropertyDescriptor;
import java.io.*;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * Created by Administrator on 2016/6/23.
 */
public class BaseUtil {

    /**
     * 获取properties配置文件
     *
     * @param propName 属性名
     * @return
     * @throws IOException 用法：getPropValue("name")
     */
    public static String getPropValue(String propName) throws IOException {
        String propValue = "";
        InputStream path = Thread.currentThread().getContextClassLoader().getResourceAsStream("conf/profile.properties");
        Properties pro = new Properties();
        pro.load(path);
        propValue = pro.getProperty(propName);
        return propValue;
    }

    /**
     * 将bean转成map
     *
     * @param obj
     * @return
     */
    public static Map<String, Object> beanToMap(Object obj) {
        Map<String, Object> params = new HashMap<String, Object>(0);
        try {
            PropertyUtilsBean propertyUtilsBean = new PropertyUtilsBean();
            PropertyDescriptor[] descriptors = propertyUtilsBean.getPropertyDescriptors(obj);
            for (int i = 0; i < descriptors.length; i++) {
                String name = descriptors[i].getName();
                if (!"class".equals(name)) {
                    params.put(name, propertyUtilsBean.getNestedProperty(obj, name));
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return params;
    }

    public static String DataTable2Json(DataTable dt) {
        StringBuilder jsonBuilder = new StringBuilder();
        jsonBuilder.append("{\"");
        jsonBuilder.append("dbs");
        jsonBuilder.append("\":");
        jsonBuilder.append(dt.getTotalRowNum() + ",");
        jsonBuilder.append("\"");
        jsonBuilder.append("db");
        jsonBuilder.append("\":[");
        for (int i = 0; i < dt.getDataRows().size(); i++) {
            jsonBuilder.append("{");
            for (int j = 0; j < dt.getDataColumns().size(); j++) {
                String dbname = dt.getDataColumns().get(j).getName();
                jsonBuilder.append("\"");
                jsonBuilder.append(dbname);
                jsonBuilder.append("\":\"");
                jsonBuilder.append(dt.getDataRows().get(i).get(dbname));
                jsonBuilder.append("\",");
            }
            jsonBuilder.deleteCharAt(jsonBuilder.length() - 1);
            jsonBuilder.append("},");
        }
        jsonBuilder.deleteCharAt(jsonBuilder.length() - 1);
        jsonBuilder.append("]}");
        return jsonBuilder.toString();
    }

    /**
     * json定位key查询value
     *
     * @param map  Map<String, Object> map
     * @param path 例："MsgBody/MsgMainInfo/yzjhkssj" 逐层递归 带数组的是“MsgBody/MsgDetailInfo[0]/ypmc” "[0]"
     * @return
     * @throws Exception
     */
    public static Object findJosnPath(Map<String, Object> map, String path) throws Exception {
        String[] paths = path.split("/");
        Map<String, Object> temp = map;
        List<Map<String, Object>> list = null;
        for (int i = 0; i < paths.length; i++) {
            String p = paths[i];
            if (i == paths.length - 1) {
                return temp.get(p);
            }
            //detail[0]
            if (p.charAt(p.length() - 1) == ']') {
                p = p.substring(0, p.length() - 1);
                String[] keyAndIndex = p.split("\\[");
                String key = keyAndIndex[0];
                int index = Integer.parseInt(keyAndIndex[1]);
                list = (List<Map<String, Object>>) temp.get(key);
                temp = list.get(index);
            } else {
                temp = (Map<String, Object>) temp.get(paths[i]);
            }
            if (temp == null)
                throw new Exception("path is error");
        }
        return null;
    }

    public static String getEncoding(String str) {
        String encode = "GB2312";
        try {
            if (str.equals(new String(str.getBytes(encode), encode))) {
                String s = encode;
                return s;
            }
        } catch (Exception exception) {
        }
        encode = "ISO-8859-1";
        try {
            if (str.equals(new String(str.getBytes(encode), encode))) {
                String s1 = encode;
                return s1;
            }
        } catch (Exception exception1) {
        }
        encode = "UTF-8";
        try {
            if (str.equals(new String(str.getBytes(encode), encode))) {
                String s2 = encode;
                return s2;
            }
        } catch (Exception exception2) {
        }
        encode = "GBK";
        try {
            if (str.equals(new String(str.getBytes(encode), encode))) {
                String s3 = encode;
                return s3;
            }
        } catch (Exception exception3) {
        }
        return "";
    }

    /**
     * 两个时间相差距离多少天多少小时多少分多少秒
     *
     * @param str1 时间参数 1 格式：1990-01-01 12:00:00
     * @param str2 时间参数 2 格式：2009-01-01 12:00:00
     * @return String 返回值为：xx天xx小时xx分xx秒
     */
    public static String getDistanceTime(String str1, String str2) {
        DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date one;
        Date two;
        long day = 0;
        long hour = 0;
        long min = 0;
        long sec = 0;
        try {
            one = df.parse(str1);
            two = df.parse(str2);
            long time1 = one.getTime();
            long time2 = two.getTime();
            long diff;
            if (time1 < time2) {
                diff = time2 - time1;
            } else {
                diff = time1 - time2;
            }
            day = diff / (24 * 60 * 60 * 1000);
            hour = (diff / (60 * 60 * 1000) - day * 24);
            min = ((diff / (60 * 1000)) - day * 24 * 60 - hour * 60);
            sec = (diff / 1000 - day * 24 * 60 * 60 - hour * 60 * 60 - min * 60);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        if (day == 0) {
            if (hour == 0) {
                return min + "分";// + sec + "秒";
            }
            return hour + "时" + min + "分";// + sec + "秒";
        }
        return day + "天" + hour + "时" + min + "分";// + sec + "秒";
    }

    /**
     * 读取txt文件的内容
     *
     * @param file 想要读取的文件对象
     * @return 返回文件内容
     */
    public static String readFileByLines(File file) {
        StringBuilder result = new StringBuilder();
        BufferedReader reader = null;
        try {
            reader = new BufferedReader(new FileReader(file));//构造一个BufferedReader类来读取文件
            String s = null;
            while ((s = reader.readLine()) != null) {//使用readLine方法，一次读一行
                result.append(s + "\n");
            }
            reader.close();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (reader != null) {
                try {
                    reader.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return result.toString();
    }

    /**
     * 解析页面传入的Table增删改信息
     *
     * @param list 页面传入的Table信息
     * @return map 将传入的信息解析后返回
     */
    public static Map<String, Object> analysisJson(List<LinkedHashMap<String, Object>> list) {
        Map<String, Object> map = new HashMap<String, Object>();
        List<Map<String, Object>> listNew = new ArrayList<Map<String, Object>>();
        List<Map<String, Object>> listUpdate = new ArrayList<Map<String, Object>>();
        List<Map<String, Object>> listDelete = new ArrayList<Map<String, Object>>();
        if (list != null) {
            for (int i = 0; i < list.size(); i++) {
                Map<String, Object> map1 = list.get(i);
                // 获取新增数据
                if ("rsNew".equals(map1.get("$status"))) {
                    map1.remove("$status");
                    listNew.add(map1);
                    continue;
                }
                // 获取删除数据
                if ("rsDelete".equals(map1.get("$status"))) {
                    map1.remove("$status");
                    listDelete.add(map1);
                    continue;
                }
                // 获取修改数据
                if ("rsUpdate".equals(map1.get("$status"))) {
                    map1.remove("$status");
                    listUpdate.add(map1);
                    continue;
                }
            }
            map.put("New", listNew);
            map.put("Delete", listDelete);
            map.put("Update", listUpdate);
        }
        return map;
    }

    /**
     * 去掉UUID的-
     *
     * @return
     */
    public static String createUUID() {
        String uuid = UUID.randomUUID().toString();
        uuid = uuid.replace("-", "");
        return uuid;
    }

    /**
     * 八位UUID
     */
    public static String[] chars = new String[]{"a", "b", "c", "d", "e", "f",
            "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s",
            "t", "u", "v", "w", "x", "y", "z", "0", "1", "2", "3", "4", "5",
            "6", "7", "8", "9", "A", "B", "C", "D", "E", "F", "G", "H", "I",
            "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V",
            "W", "X", "Y", "Z"};

    public static String generateShortUuid() {
        StringBuffer shortBuffer = new StringBuffer();
        String uuid = UUID.randomUUID().toString().replace("-", "");
        for (int i = 0; i < 8; i++) {
            String str = uuid.substring(i * 4, i * 4 + 4);
            int x = Integer.parseInt(str, 16);
            shortBuffer.append(chars[x % 0x3E]);
        }
        return shortBuffer.toString();

    }

    /**
     * 获取IP地址
     *
     * @param request
     * @return
     */
    public static String getIPAddr(HttpServletRequest request) {
        String ip = request.getHeader("x-forwarded-for");
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("WL-Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getRemoteAddr();
        }
        if (ip.equals("0:0:0:0:0:0:0:1")) {
            ip = "127.0.0.1";
        }
        return ip;
    }

    /**
     * 获取MAC地址
     *
     * @param ip
     * @return
     */
    public String getMACAddr(String ip) {
        String str = "";
        String macAddress = "";
        try {
            Process p = Runtime.getRuntime().exec("nbtstat -A " + ip);
            InputStreamReader ir = new InputStreamReader(p.getInputStream());
            LineNumberReader input = new LineNumberReader(ir);
            for (int i = 1; i < 100; i++) {
                str = input.readLine();
                if (str != null) {
                    if (str.indexOf("MAC Address") > 1) {
                        macAddress = str.substring(str.indexOf("MAC") + 14, str.length());
                        break;
                    }
                    if (str.indexOf("MAC 地址") > 1) {
                        macAddress = str.substring(str.indexOf("MAC 地址") + 9, str.length());
                        break;
                    }
                }
            }
        } catch (IOException e) {
            e.printStackTrace(System.out);
        }
        return macAddress;
    }
}
